package com.suyuan.service.impl;

import com.suyuan.dao.CustomCartItemMapper;
import com.suyuan.dao.CustomerCartMapper;
import com.suyuan.dao.ProductInfoMapper;
import com.suyuan.entity.CustomCartItem;
import com.suyuan.entity.CustomerCart;
import com.suyuan.entity.CustomerCartExample;
import com.suyuan.entity.ProductInfo;
import com.suyuan.service.CustomCartService;
import com.suyuan.vo.CustomerCartVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created by yang on 2018/4/6.
 */
@Service(value = "customCartService")
@Transactional
public class CustomCartServiceImpl implements CustomCartService{
    @Resource
    private CustomerCartMapper customerCartMapper;
    @Resource
    private CustomCartItemMapper itemMapper;
    @Resource
    private ProductInfoMapper productInfoMapper;

    /**
     * 根据客户id查询购物车和所有购物项
     * @param id
     * @return
     */
    public CustomerCartVO findByCusId(Integer id) {
        CustomerCartExample example = new CustomerCartExample();
        CustomerCartExample.Criteria criteria = example.createCriteria();
        criteria.andCustomerIdEqualTo(id);
        List<CustomerCart> carts = customerCartMapper.selectByExample(example);

        CustomerCart cart = carts.get(0);
        List<CustomCartItem> items = itemMapper.findByCarId(id);

        return new CustomerCartVO(cart,items);
    }


    /**
     * 添加商品进购物车中
     * @param item
     * @return
     */
    public boolean addCartItem(CustomCartItem item) throws Exception{
        if(item.getCartId() == null || item.getProductId() == null || item.getProCount() == null){
            return false;
        }

        //购物车对象
        CustomerCart cart = customerCartMapper.selectByPrimaryKey(item.getCartId());
        if(cart == null){
            return false;
        }

        //购物项小计
        ProductInfo p = productInfoMapper.selectByPrimaryKey(item.getProductId());
        item.setSubtotal(new BigDecimal(p.getSellprice() * item.getProCount()));

        //如果购物车已有同一种商品，则不创建新的购物项，直接添加数量和小计
        CustomCartItem existItem = itemMapper.existItem(item.getCartId(),item.getProductId());
        if(existItem == null){

            //购物车中不存在该商品，则保存新的购物项
            Integer count = item.getProCount();
            ProductInfo productInfo = productInfoMapper.selectByPrimaryKey(item.getProductId());
            item.setProductName(productInfo.getProductname());
            item.setProductImage(productInfo.getImagesrc());
            item.setProPrice(productInfo.getProcprice());
            item.setSubtotal(new BigDecimal(count*productInfo.getSellprice()));
            itemMapper.insert(item);
        }else{
            //购物车中已存在同款商品，数量和价钱叠加
            int newCount = existItem.getProCount() + item.getProCount();
            BigDecimal newSubtotal = existItem.getSubtotal().add(item.getSubtotal());
            existItem.setProCount(newCount);
            existItem.setSubtotal(newSubtotal);
            System.out.println("existItem:"+existItem);
            itemMapper.updateItem(existItem);
        }

        //购物车加上购物项小计
        cart.setTotal(cart.getTotal().add(item.getSubtotal()));
        //更新数据
        customerCartMapper.updateByPrimaryKey(cart);
        return true;
    }

    public boolean deleteById(Integer id) {
        int code = 0;
        try {
            CustomCartItem item = itemMapper.findById(id);
            CustomerCart cart = customerCartMapper.selectByPrimaryKey(item.getCartId());
            cart.setTotal(cart.getTotal().subtract(item.getSubtotal()));
            customerCartMapper.updateByPrimaryKey(cart);
            itemMapper.delete(id);
            code = 1;
        } catch (Exception e) {
            code = 0;
            e.printStackTrace();
        }
        if(code == 1){
            return true;
        }
        return false;
    }

    public boolean clearCart(Integer cartId) {
        int code = 0;
        try {
            itemMapper.clearCart(cartId);
            CustomerCart cart = customerCartMapper.selectByPrimaryKey(cartId);
            cart.setTotal(BigDecimal.ZERO);
            customerCartMapper.updateByPrimaryKey(cart);
            code = 1;
        } catch (Exception e) {
            e.printStackTrace();
            code = 0;
        }
        if(code == 1){
            return true;
        }
        return false;
    }

    /**
     * 更改购物车中购物项数量
     * @param id
     * @param count
     * @return
     */
    public boolean changeItemCount(Integer id, Integer count) throws Exception{
        CustomCartItem item = itemMapper.findById(id);
        if(item == null){
            System.out.println("购物项不存在");
            throw new Exception("购物项不存在");
        }
        CustomerCartExample example = new CustomerCartExample();
        CustomerCartExample.Criteria criteria = example.createCriteria();
        criteria.andCartIdEqualTo(item.getCartId());
        List<CustomerCart> customerCarts = customerCartMapper.selectByExample(example);
        if(customerCarts.size() < 1 || customerCarts == null){
            throw new Exception("购物车不存在");
        }
        CustomerCart cart = customerCarts.get(0);
        try {
            item.setProCount(count);
            ProductInfo product = productInfoMapper.selectByPrimaryKey(item.getProductId());
            Float procprice = product.getProcprice();

            BigDecimal oldSub = item.getSubtotal();
            BigDecimal newSub = new BigDecimal(procprice * count);
            BigDecimal diff = newSub.subtract(oldSub);

            //小计为数量*单价
            item.setSubtotal(newSub);

            //购物车总计
            cart.setTotal(cart.getTotal().add(diff));
            itemMapper.updateItem(item);
            customerCartMapper.updateByPrimaryKey(cart);

        } catch (Exception e) {
            e.printStackTrace();
            throw  new Exception("数量更新过程出异常啦");
        }
        return true;
    }
}
